import { atomWithProxy } from 'jotai-valtio';
import { proxy, subscribe } from 'valtio';

export interface VulnerableStore {
  passed: number;
  passedVulnerable: string[];
}

// 初始化vulnerableProxy
const initVulnerableProxy = (): VulnerableStore => {
  const vulState = localStorage.getItem('vulnerable');
  if (!vulState) {
    const vulJsonState = JSON.stringify({ passed: 0, passedVulnerable: [] });
    localStorage.setItem('vulnerable', vulJsonState);
    return { passed: 0, passedVulnerable: [] };
  } else {
    return JSON.parse(vulState);
  }
};

export const vulnerableProxy = proxy<VulnerableStore>(initVulnerableProxy());

// 完成漏洞关卡
export const finishVulnerable = (vulnerableName: string) => {
  vulnerableProxy.passed += 1;
  vulnerableProxy.passedVulnerable.push(vulnerableName);
};

// 重置单个漏洞关卡
export const resetSingleVulnerable = (vulnerableName: string) => {
  const vulIndex = vulnerableProxy.passedVulnerable.indexOf(vulnerableName);
  if (vulIndex !== -1) {
    vulnerableProxy.passed -= 1;
    vulnerableProxy.passedVulnerable.splice(vulIndex, 1);
  }
};

// 重置所有漏洞关卡
export const resetVulnerable = () => {
  vulnerableProxy.passed = 0;
  vulnerableProxy.passedVulnerable = [];
};

// 每当漏洞关卡改变时保存到localStorage
subscribe(vulnerableProxy, () => {
  localStorage.setItem('vulnerable', JSON.stringify(vulnerableProxy));
});

export default atomWithProxy(vulnerableProxy);
